package br.albatroz.bean;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.persistence.Query;

import br.albatroz.et.Partida;
import br.albatroz.et.Time;

@ManagedBean(name = "PartidaBean")
public class PartidaBean extends AbstractBean {

	private Partida partida;
	private long homeId;

	private long visitorId;

	// private Select

	public PartidaBean() {
		partida = new Partida();
	}

	public Partida getPartida() {
		return partida;
	}

	public void setPartida(Partida partida) {
		this.partida = partida;
	}

	public List<Partida> getAllPartida() {
		return getEm().createQuery("select p from Partida as p").getResultList();
	}
	
	public List<Time> getAllTime() {
		return getEm().createQuery("select t from Time as t").getResultList();
	}

	public List<SelectItem> getListTimes() {
		List<SelectItem> items = new ArrayList<SelectItem>();

		for (Time t : getAllTime()) {
			items.add(new SelectItem(t.getId(), t.getName()));
		}

		return items;
	}

	public long getHomeId() {
		return homeId;
	}

	public void setHomeId(long homeId) {
		this.homeId = homeId;
	}

	public long getVisitorId() {
		return visitorId;
	}

	public void setVisitorId(long visitorId) {
		this.visitorId = visitorId;
	}

	public String editPartida() {
		try {
			long id = Long.valueOf((String) getExternalParam().get("partidaId"));
			Query q = getEm().createQuery(
					"select p from Partida as p where p.id = :id");
			q.setParameter("id", id);
			partida = (Partida) q.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

		return "add-partida";

	}

	public String savePartida(){
		getEm().getTransaction().begin(); 
		try{			  
	        getEm().merge(partida);       
	        getEm().getTransaction().commit();
		}catch(Exception e){
			e.printStackTrace();
			getEm().getTransaction().rollback();
			return "error";
		}
		
		partida = new Partida();
		
        return "rep-partidas";
	}
	
	public void changeHome(ValueChangeEvent value) {
		homeId = Long.valueOf(value.getNewValue().toString());
		 
		for (Time t : getAllTime()) {
			if (t.getId() == homeId) {
				partida.setHome(t);
			}
		}
	}
	
	public void changeVisitor(ValueChangeEvent value) {
		visitorId = Long.valueOf(value.getNewValue().toString());
		 
		for (Time t : getAllTime()) {
			if (t.getId() == visitorId) {
				partida.setVisitor(t);
			}
		}
	}
}
